package com.honghu.villagepost.dialog;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;

import com.ada.common.util.CollectionUtil;
import com.blankj.utilcode.util.ToastUtils;
import com.honghu.villagepost.R;
import com.honghu.villagepost.activity.AddrActivity;
import com.honghu.villagepost.activity.LogisticsOrderDetailsActivity;
import com.honghu.villagepost.activity.LogisticsOrderSettleActivity;
import com.honghu.villagepost.api.ApiService;
import com.honghu.villagepost.callback.DialogCallback;
import com.honghu.villagepost.callback.LzyResponse;
import com.honghu.villagepost.entity.Addr;
import com.honghu.villagepost.entity.request.LogisticsOrderReq;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.Map;


/**
 * Desc:同城代寄-弹框
 * <p>
 * Author: [李豫]
 * Date: 2018-08-02
 * Copyright: Copyright (c) 2010-2018
 * Updater:
 * Update Time:
 * Update Comments:
 */
public class OrderCityDialog extends DialogFragment implements View.OnClickListener {

    private TextView mTvSendName;
    private TextView mTvPhone;
    private TextView mTvAddr;
    private EditText mEtNum;
    private TextView mTvOrder;
    private int mSelectAddrType;
    private Addr mSendAddr;

    public static OrderCityDialog newInstance() {
        OrderCityDialog payMethodDialog = new OrderCityDialog();
        return payMethodDialog;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setCancelable(true);
        setStyle(DialogFragment.STYLE_NORMAL, R.style.customDialog);

        EventBus.getDefault().register(this);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getDialog().setCanceledOnTouchOutside(true);
        Window window = getDialog().getWindow();
        window.setGravity(Gravity.CENTER);
        window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View dialogView = inflater.inflate(R.layout.dialog_order_city, container, false);

        mTvSendName = dialogView.findViewById(R.id.tv_send_name);
        mTvPhone = dialogView.findViewById(R.id.tv_phone);
        mTvAddr = dialogView.findViewById(R.id.tv_addr);
        mEtNum = dialogView.findViewById(R.id.et_num);
        dialogView.findViewById(R.id.tv_change_addr).setOnClickListener(this);
        mTvOrder = dialogView.findViewById(R.id.tv_order);
        mTvOrder.setOnClickListener(this);
        dialogView.findViewById(R.id.iv_reduce).setOnClickListener(this);
        dialogView.findViewById(R.id.iv_add).setOnClickListener(this);

        initData();
        return dialogView;
    }

    private void initData() {
        ApiService.user_address(this, "", 1, new DialogCallback<LzyResponse<Addr>>() {
            @Override
            public void onSuccess(Response<LzyResponse<Addr>> response) {
                List<Addr> records = response.body().data.records;
                Addr defaultAddr = getDefaultAddr(records);
                if (defaultAddr != null) {
                    mSendAddr = defaultAddr;
                    mTvSendName.setText(defaultAddr.name);
                    mTvPhone.setText(defaultAddr.mobile);
                    mTvAddr.setText(defaultAddr.city + defaultAddr.district + defaultAddr.street + defaultAddr.address);
                }
            }
        });
    }

    private Addr getDefaultAddr(List<Addr> records) {
        if (!CollectionUtil.isEmptyOrNull(records)) {
            for (Addr addr : records) {
                if (addr.defaultAddr) {
                    return addr;
                }
            }
            return records.get(0);
        }
        return null;
    }

    public void show(FragmentManager manager) {
        if (!isShowing()) {
            show(manager, OrderCityDialog.class.getSimpleName());
        }
    }

    public boolean isShowing() {
        if (getDialog() != null && getDialog().isShowing()) {
            return true;
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.tv_change_addr) {
            mSelectAddrType = 1;
            AddrActivity.Companion.self(getActivity(), true);
        } else if (viewId == R.id.tv_order) {
            createOrder();
        } else if (viewId == R.id.tv_rece_name) {
            mSelectAddrType = 2;
            AddrActivity.Companion.self(getActivity(), true);
        } else if (viewId == R.id.iv_reduce) {
            reduce();
        } else if (viewId == R.id.iv_add) {
            add();
        }
    }

    private void add() {
        int money = 0;
        String num = mEtNum.getText().toString();
        if (!TextUtils.isEmpty(num)) {
            money = Integer.parseInt(num);
        }

        money = money + 1;
        String moneyStr = String.valueOf(money);
        mEtNum.setText(moneyStr);
        mEtNum.setSelection(moneyStr.length());

        settleMoney(money);
    }

    private void settleMoney(int money) {
        int totalMoney = 4;
        if (money > 1) {
            totalMoney = 4 + (money - 1) * 2;
        }
        mTvOrder.setText(String.format("下单(支付%d元)", totalMoney));
    }

    private void reduce() {
        int money = 0;
        String num = mEtNum.getText().toString();
        if (!TextUtils.isEmpty(num)) {
            money = Integer.parseInt(num);
        }
        if (money > 1) {
            money = money - 1;
        } else {
            money = 1;
        }

        String moneyStr = String.valueOf(money);
        mEtNum.setText(moneyStr);
        mEtNum.setSelection(moneyStr.length());

        settleMoney(money);
    }

    private void createOrder() {
        try {
            if (mSendAddr == null) {
                ToastUtils.showShort("请补全寄件人地址");
                return;
            }

            LogisticsOrderReq logisticsOrderReq = new LogisticsOrderReq();
            logisticsOrderReq.setType(LogisticsOrderSettleActivity.Companion.getTYPE_CITY_SEND());
            logisticsOrderReq.setSenderAddress(mSendAddr);
            String numStr = mEtNum.getText().toString();
            logisticsOrderReq.setQuantity(Integer.parseInt(numStr));
            ApiService.logistics_orde_create(this, logisticsOrderReq, new DialogCallback<LzyResponse<Map<String, Object>>>() {
                @Override
                public void onSuccess(Response<LzyResponse<Map<String, Object>>> response) {
                    ToastUtils.showShort("下单成功");
                    dismiss();
                }
            });
        } catch (Exception e) {

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void addrEven(Addr addr) {
        if (addr != null) {
            if (mSelectAddrType == 1) {
                mSendAddr = addr;
                mTvSendName.setText(addr.name);
                mTvPhone.setText(addr.mobile);
                mTvAddr.setText(addr.city + addr.district + addr.street + addr.address);
            }
        }
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}

